package com.jsmile.cloud.goodscenter.spu.model;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.jsmile.cloud.goodscenter.api.req.spu.ReqSpecAdd;
import com.jsmile.cloud.goodscenter.api.res.ResSpec;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年06月04日 03:56:49
 */
@ApiModel
@Data
@TableName("t_sku_spec")
public class SkuSpec extends Model<SkuSpec> {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "id")
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @ApiModelProperty(value = "sku_id")
    private Long skuId;
    @ApiModelProperty(value = "spu_id")
    private Long spuId;
    @ApiModelProperty(value = "规格id")
    private Long specId;
    @ApiModelProperty(value = "规格名")
    private String specName;
    @ApiModelProperty(value = "规格值")
    private String specValue;
    @ApiModelProperty(value = "租户id")
    private Long tenantId;
    @ApiModelProperty(value = "平台id")
    private Integer platformId;
    @ApiModelProperty(value = "业务id")
    private Integer bizCode;
    @ApiModelProperty(value = "创建时间")
    private Date createTime;
    @ApiModelProperty(value = "更新时间")
    private Date updateTime;

    public static List<SkuSpec> create(List<ReqSpecAdd> specs, Long tenantId, Long spuId, Long skuId) {
        return specs.stream().map(x -> {
            SkuSpec skuSpec = BeanUtil.toBean(x, SkuSpec.class);
            skuSpec.setCreateTime(new Date());
            skuSpec.setTenantId(tenantId);
            skuSpec.setSpuId(spuId);
            skuSpec.setSkuId(skuId);
            return skuSpec;
        }).collect(Collectors.toList());
    }

    public static List<ResSpec> getResSpecs(List<SkuSpec> skuSpecs) {
        if (CollectionUtils.isEmpty(skuSpecs)) {
            return null;
        }
        Map<String, List<SkuSpec>> groupBy = skuSpecs.stream().collect(Collectors.groupingBy(SkuSpec::getSpecName));
        return groupBy.keySet().stream().map(x -> {
            ResSpec resSpec = new ResSpec();
            resSpec.setSpecName(x);
            resSpec.setSpecGroups(groupBy.get(x).stream().map(y -> BeanUtil.toBean(y, ResSpec.ResSpecGroup.class)).distinct().collect(Collectors.toList()));
            return resSpec;
        }).collect(Collectors.toList());
    }
}
